package com.fenghuajueli.lib_net;


import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;

import okhttp3.logging.HttpLoggingInterceptor;

public class LoggingInterceptor implements HttpLoggingInterceptor.Logger {
    private StringBuffer mMessage = new StringBuffer();

    @Override
    public void log(String message) {
        // 请求或者响应开始
        try {
            if (message.startsWith("--> POST")) {
                mMessage.setLength(0);
                mMessage.append(" ");
                mMessage.append("\r\n");
            }
            if (message.startsWith("--> GET")) {
                mMessage.setLength(0);
                mMessage.append(" ");
                mMessage.append("\r\n");
            }
            // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
            if ((message.startsWith("{") && message.endsWith("}"))
                    || (message.startsWith("[") && message.endsWith("]"))) {
                message = GsonUtils.toJson(message);
            }
            mMessage.append(message.concat("\n"));
            // 请求或者响应结束，打印整条日志
            if (message.startsWith("<-- END HTTP")) {
                LogUtils.e("LoggingInterceptor", mMessage.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}